home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / admin / peakprocs < prev    next >
Encoding:
AWK Script  |  1997-08-26  |  31.9 KB  |  883 lines

  1. #!/usr/local/bin/gawk -f
  2. #!/usr/bin/awk -f
  3. # @(#) peakprocs.gawk 2.1 94/03/09
  4. # 91/07/08 John H. DuBois III (john@armory.com)
  5. # 91/07/26 Completely changed method of operation so that a sort on all
  6. #          processes and storing of all processes in an awk array
  7. #          is no longer neccessary
  8. # 94/02/12 Added all options, cleaned up a bit, fixed assorted queue bugs
  9. # 94/03/09 Use gawk so - options can be given
  10.  
  11. # Use gawk for /dev/stdin
  12.  
  13. # Day is the number of days before the end of the process log, in seconds
  14. # I points to the most recent start time
  15.  
  16. BEGIN {
  17.     Name = "peakprocs"
  18.     Usage = "Usage: " Name " [-hipr] [-a<options>] [acctcom-output]"
  19.     ARGC = Opts(Name,Usage,"a:hiprx",0)
  20.     if ("h" in Options) {
  21.     print \
  22. Name ": Print the peak number of processes that ran.\n"\
  23. Usage "\n"\
  24. Name " uses the process accounting logs to determine the peak number of\n"\
  25. "processes that were executing at any time during the interval covered by\n"\
  26. "the logs.  The peak, and the time at which it occurred (relative to the\n"\
  27. "time of the end of the logs) is printed after all input has been\n"\
  28. "processed.\n"\
  29. "If no filenames are given, acctcom is run on the current process accounting\n"\
  30. "log and its output is used.  If filenames are given, they should be the\n"\
  31. "output of 'acctcom -b' (due to the way " Name " calculates peaks, input\n"\
  32. "must be in reverse order of time of process exit).  The peak number of\n"\
  33. "processes run by particular users, on particular ttys, etc. can be\n"\
  34. "determined by giving the appropriate selection options to acctcom.\n"\
  35. "Options:\n"\
  36. "-a: Pass <options> to acctcom when running it.\n"\
  37. "-h: Print this help.\n"\
  38. "-i: The standard input is read.\n"\
  39. "-p: Print the number of process running each time the peak increases.\n"\
  40. "-r: Print the number of processes running each time it changes."
  41.     exit(0)
  42.     }
  43.  
  44.     ShowPeak = "p" in Options
  45.     Running = "r" in Options
  46.     Debug = "x" in Options
  47.     if ("i" in Options) {
  48.     ARGC = 2
  49.     ARGV[1] = "/dev/stdin"
  50.     }
  51.     if (ARGC > 1)
  52.     for (i = 1; i < ARGC; i++) {
  53.         File = ARGV[i]
  54.         while ((getline < File) == 1)
  55.         ProcInput()
  56.         close(File)
  57.     }
  58.     else {
  59.     # Have to give acctcom /dev/tty as input because it wants to stat
  60.     # fd 0 & gawk screws it up
  61.     Cmd = "acctcom -b " Options["a"] " < /dev/tty"
  62.     if (Debug)
  63.         printf "Running command: <%s>\n",Cmd
  64.     while ((Cmd | getline) == 1)
  65.         ProcInput()
  66.     close(Cmd)
  67.     }
  68.     if (!Peak)
  69.     print "No procs."
  70.     else if (!ShowPeak)
  71.     printf "Peak processes: %d (on %s).\n",Peak,ToTime(PeakTime)
  72. }
  73.  
  74. # Globals: $*, Procs, Starts[], Peak, PeakTime, LastProcs
  75. function ProcInput(  ) {
  76.     if ($2 == "START" || $2 == "USER")    # skip heading
  77.     return
  78.     CalcStartEnd($5,$6)    # sets globals StartTime and EndTime
  79.     while ((EndTime < Q["Head"]) && (Q["Head"] != "")) {
  80.     Procs -= Starts[Time = Pop(Q)]
  81.     delete Starts[Time]
  82.     }
  83.     if (Debug)
  84.     print "Inserting start time into queue."
  85.     Insert(Q,StartTime)
  86.     if (Debug)
  87.     print "Incrementing start time counter."
  88.     Starts[StartTime]++
  89.     if (++Procs > Peak) {
  90.     Peak = Procs
  91.     PeakTime = EndTime
  92.     if (ShowPeak)
  93.         printf("Peak processes: %d (on %s).\n",
  94.         Peak,ToTime(PeakTime))
  95.     }
  96.     if (Running) {
  97.     if (Procs != LastProcs)
  98.         printf("Processes: %d (on %s).\n",
  99.         Procs,ToTime(EndTime))
  100.     LastProcs = Procs
  101.     }
  102. }
  103.  
  104. # sets globals StartTime and EndTime
  105. # Sets/uses globals LastEnd, Day
  106. function CalcStartEnd(EndField,RunField,  EndElem) {
  107.     split(EndField,EndElem,":")    # Field 5 is process end time
  108.     EndTime = EndElem[1] * 3600 + EndElem[2] * 60 + EndElem[3]
  109.     # We're unlikely to go for 1000 seconds without any processes terminating
  110.     if (((EndTime - LastEnd) > 1000) && (LastEnd != "")) {
  111.     Day -= 86400
  112.     if (Debug)
  113.         printf "Day reduced to %d.\n",Day
  114.     }
  115.     LastEnd = EndTime
  116.     EndTime += Day
  117.     StartTime = EndTime - int(RunField + 0.99)   # run time, in seconds
  118.     if (Debug)
  119.     printf "Start time: %d; end time: %d\n",StartTime,EndTime
  120. }
  121.  
  122. function ToTime(Time,  Days,Minutes) {
  123.     Days = Time / 86400
  124.     Time %= 86400
  125.     if (Time < 0) {
  126.     Time += 86400
  127.     Days -= 1
  128.     }
  129.     Minutes = (Time % 3600) / 60
  130.     return sprintf("day %d, %02d:%02d:%02d",Days,
  131.     Time / 3600,Minutes,Time % 60)
  132. }
  133.  
  134. # Q is a linked list of values formed from an array where the 
  135. # value of each element is the index of the next element.
  136. # The queue is maintained with the highest (more positive) value
  137. # at the head of the queue.
  138. # The value of the last element is null.
  139. # Values that are already in Q are discarded.
  140. # Q["Head"] is the index of the element at the top of the list;
  141. # the value "Head" and the null value should not be used.
  142. # Value is the value to be added to the list
  143. # An empty queue has a null Q["Head"] and no elements.
  144.  
  145. function Insert(Q,Value,  QHead,Next) {
  146.     if (Value == "" || Value == "Head")
  147.     return -1
  148.     QHead = Q["Head"]
  149.     # Insert element at head of queue
  150.     if ((QHead == "") || (Value > QHead)) {
  151.     Q[Value] = QHead
  152.     Q["Head"] = Value
  153.     return 0
  154.     }
  155.     Next = Q[QHead]
  156.     if (Debug)
  157.     print "Searching for position to insert element at."
  158.     while ((Next > Value) && (Next != "")) {
  159.     QHead = Next
  160.     Next = Q[QHead]
  161.     if (Next != "" && Next >= QHead) {
  162.         printf "Corrupt queue! Current value = %s; next value = %s.\n",
  163.         QHead,Next
  164.         PrintQ(Q)
  165.         exit(1)
  166.     }
  167.     }
  168.     # At his point, QHead is larger than Value,
  169.     # and Next is either null or =< Value
  170.     if (Value == Next)
  171.     return
  172.     if (Debug)
  173.     printf "Inserting %s after %s and before %s\n",Value,QHead,Next
  174.     Q[QHead] = Value
  175.     Q[Value] = Next
  176.     return 0
  177. }
  178.  
  179. function PrintQ(Q,  QHead) {
  180.     QHead = Q["Head"]
  181.     while (QHead != "") {
  182.     printf "%s ",QHead
  183.     QHead = Q[QHead]
  184.     }
  185.     print ""
  186. }
  187.  
  188. # Returns the value at the head of Q, or null of Q is empty.
  189. # Removes the value from Q.
  190. function Pop(Q,  QHead) {
  191.     QHead = Q["Head"]
  192.     if (QHead != "") {
  193.     Q["Head"] = Q[QHead]
  194.     delete Q[QHead]
  195.     }
  196.     return QHead
  197. }
  198.  
  199. ### Start of ProcArgs library
  200. # @(#) ProcArgs 1.11 96/12/08
  201. # 92/02/29 john h. dubois iii (john@armory.com)
  202. # 93/07/18 Added "#" arg type
  203. # 93/09/26 Do not count -h against MinArgs
  204. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  205. #          Removed meaning of "+" or "-" by itself.
  206. # 94/03/08 Added & option and *()< option types.
  207. # 94/04/02 Added NoRCopt to Opts()
  208. # 94/06/11 Mark numeric variables as such.
  209. # 94/07/08 Opts(): Do not require any args if h option is given.
  210. # 95/01/22 Record options given more than once.  Record option num in argv.
  211. # 95/06/08 Added ExclusiveOptions().
  212. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  213. #          Expand $VARNAME at the start of its filenames.
  214. #          Let varname=0 and -option- turn off an option.
  215. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  216. #          of the vars should be searched for in the environment.
  217. #          Check for duplicate rcfiles.
  218. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  219. #          now return various negatives values on error, not just -1, and
  220. #          Opts() may set Err to various positive values, not just 1.
  221. #          Added AllowUnrecOpt.
  222. # 96/05/23 Check type given for & option
  223. # 96/06/15 Re-port to awk
  224. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  225. #          used by other functions.
  226. # 96/10/15 Added OptChars
  227. # 96/11/01 Added exOpts arg to Opts()
  228. # 96/11/16 Added ; type
  229. # 96/12/08 Added Opt2Set() & Opt2Sets()
  230. # 96/12/27 Added CmdLineOpt()
  231.  
  232. # optlist is a string which contains all of the possible command line options.
  233. # A character followed by certain characters indicates that the option takes
  234. # an argument, with type as follows:
  235. # :    String argument
  236. # ;    Non-empty string argument
  237. # *    Floating point argument
  238. # (    Non-negative floating point argument
  239. # )    Positive floating point argument
  240. # #    Integer argument
  241. # <    Non-negative integer argument
  242. # >    Positive integer argument
  243. # The only difference the type of argument makes is in the runtime argument
  244. # error checking that is done.
  245.  
  246. # The & option is a special case used to get numeric options without the
  247. # user having to give an option character.  It is shorthand for [-+.0-9].
  248. # If & is included in optlist and an option string that begins with one of
  249. # these characters is seen, the value given to "&" will include the first
  250. # char of the option.  & must be followed by a type character other than ":"
  251. # or ";".
  252. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  253.  
  254. # Strings in argv[] which begin with "-" or "+" are taken to be
  255. # strings of options, except that a string which consists solely of "-"
  256. # or "+" is taken to be a non-option string; like other non-option strings,
  257. # it stops the scanning of argv and is left in argv[].
  258. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  259. # If an option takes an argument, the argument may either immediately
  260. # follow it or be given separately.
  261. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  262. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  263. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  264. # this feature had a flaw that caused problems in some cases.  See the OptChars
  265. # parameter to explicitly set the option-specifier characters.
  266.  
  267. # If an option that does not take an argument is given,
  268. # an index with its name is created in Options and its value is set to the
  269. # number of times it occurs in argv[].
  270.  
  271. # If an option that does take an argument is given, an index with its name is
  272. # created in Options and its value is set to the value of the argument given
  273. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  274. # If an option that takes an argument is given more than once,
  275. # Options[option-name,"count"] is incremented, and the value is assigned to
  276. # the index (option-name,instance) where instance is 2 for the second occurance
  277. # of the option, etc.
  278. # In other words, the first time an option with a value is encountered, the
  279. # value is assigned to an index consisting only of its name; for any further
  280. # occurances of the option, the value index has an extra (count) dimension.
  281.  
  282. # The sequence number for each option found in argv[] is stored in
  283. # Options[option-name,"num",instance], where instance is 1 for the first
  284. # occurance of the option, etc.  The sequence number starts at 1 and is
  285. # incremented for each option, both those that have a value and those that
  286. # do not.  Options set from a config file have a value of 0 assigned to this.
  287.  
  288. # Options and their arguments are deleted from argv.
  289. # Note that this means that there may be gaps left in the indices of argv[].
  290. # If compress is nonzero, argv[] is packed by moving its elements so that
  291. # they have contiguous integer indices starting with 0.
  292. # Option processing will stop with the first unrecognized option, just as
  293. # though -- was given except that unlike -- the unrecognized option will not be
  294. # removed from ARGV[].  Normally, an error value is returned in this case.
  295. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  296. # be found, so the number of remaining arguments is returned instead.
  297. # If OptChars is not a null string, it is the set of characters that indicate
  298. # that an argument is an option string if the string begins with one of the
  299. # characters.  A string consisting solely of two of the same option-indicator
  300. # characters stops the scanning of argv[].  The default is "-+".
  301. # argv[0] is not examined.
  302. # The number of arguments left in argc is returned.
  303. # If an error occurs, the global string OptErr is set to an error message
  304. # and a negative value is returned.
  305. # Current error values:
  306. # -1: option that required an argument did not get it.
  307. # -2: argument of incorrect type supplied for an option.
  308. # -3: unrecognized (invalid) option.
  309. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  310. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  311. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  312. {
  313. # ArgNum is the index of the argument being processed.
  314. # ArgsLeft is the number of arguments left in argv.
  315. # Arg is the argument being processed.
  316. # ArgLen is the length of the argument being processed.
  317. # ArgInd is the position of the character in Arg being processed.
  318. # Option is the character in Arg being processed.
  319. # Pos is the position in OptList of the option being processed.
  320. # NumOpt is true if a numeric option may be given.
  321.     ArgsLeft = argc
  322.     NumOpt = index(OptList,"&")
  323.     OptionNum = 0
  324.     if (OptChars == "")
  325.     OptChars = "-+"
  326.     while (OptChars != "") {
  327.     c = substr(OptChars,1,1)
  328.     OptChars = substr(OptChars,2)
  329.     OptCharSet[c]
  330.     OptTerm[c c]
  331.     }
  332.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  333.     Arg = argv[ArgNum]
  334.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  335.         break    # Not an option; quit
  336.     if (Arg in OptTerm) {
  337.         delete argv[ArgNum]
  338.         ArgsLeft--
  339.         break
  340.     }
  341.     ArgLen = length(Arg)
  342.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  343.         Option = substr(Arg,ArgInd,1)
  344.         if (NumOpt && Option ~ /[-+.0-9]/) {
  345.         # If this option is a numeric option, make its flag be & and
  346.         # its option string flag position be the position of & in
  347.         # the option string.
  348.         Option = "&"
  349.         Pos = NumOpt
  350.         # Prefix Arg with a char so that ArgInd will point to the
  351.         # first char of the numeric option.
  352.         Arg = "&" Arg
  353.         ArgLen++
  354.         }
  355.         # Find position of flag in option string, to get its type (if any).
  356.         # Disallow & as literal flag.
  357.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  358.         if (AllowUnrecOpt) {
  359.             Escape = 1
  360.             break
  361.         }
  362.         else {
  363.             OptErr = "Invalid option: " specGiven Option
  364.             return -3
  365.         }
  366.         }
  367.  
  368.         # Find what the value of the option will be if it takes one.
  369.         # NeedNextOpt is true if the option specifier is the last char of
  370.         # this arg, which means that if the option requires a value it is
  371.         # the next arg.
  372.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  373.         if (GotValue = ArgNum + 1 < argc)
  374.             Value = argv[ArgNum+1]
  375.         }
  376.         else {    # Value is included with option
  377.         Value = substr(Arg,ArgInd + 1)
  378.         GotValue = 1
  379.         }
  380.  
  381.         if (HadValue = AssignVal(Option,Value,Options,
  382.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  383.         specGiven)) {
  384.         if (HadValue < 0)    # error occured
  385.             return HadValue
  386.         if (HadValue == 2)
  387.             ArgInd++    # Account for the single-char value we used.
  388.         else {
  389.             if (NeedNextOpt) {    # option took next arg as value
  390.             delete argv[++ArgNum]
  391.             ArgsLeft--
  392.             }
  393.             break    # This option has been used up
  394.         }
  395.         }
  396.     }
  397.     if (Escape)
  398.         break
  399.     # Do not delete arg until after processing of it, so that if it is not
  400.     # recognized it can be left in ARGV[].
  401.     delete argv[ArgNum]
  402.     ArgsLeft--
  403.     }
  404.     if (compress != 0) {
  405.     dest = 1
  406.     src = argc - ArgsLeft + 1
  407.     for (count = ArgsLeft - 1; count; count--) {
  408.         ARGV[dest] = ARGV[src]
  409.         dest++
  410.         src++
  411.     }
  412.     }
  413.     return ArgsLeft
  414. }
  415.  
  416. # Assignment to values in Options[] occurs only in this function.
  417. # Option: Option specifier character.
  418. # Value: Value to be assigned to option, if it takes a value.
  419. # Options[]: Options array to return values in.
  420. # ArgType: Argument type specifier character.
  421. # GotValue: Whether any value is available to be assigned to this option.
  422. # Name: Name of option being processed.
  423. # OptionNum: Number of this option (starting with 1) if set in argv[],
  424. #     or 0 if it was given in a config file or in the environment.
  425. # SingleOpt: true if the value (if any) that is available for this option was
  426. #     given as part of the same command line arg as the option.  Used only for
  427. #     options from the command line.
  428. # specGiven is the option specifier character use, if any (e.g. - or +),
  429. # for use in error messages.
  430. # Global variables: OptErr
  431. # Return value: negative value on error, 0 if option did not require an
  432. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  433. # the arg.
  434. # Current error values:
  435. # -1: Option that required an argument did not get it.
  436. # -2: Value of incorrect type supplied for option.
  437. # -3: Bad type given for option &
  438. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  439. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  440.     # If option takes a value...    [
  441.     NumTypes = "*()#<>]"
  442.     if (Option == "&" && ArgType !~ "[" NumTypes) {    # ]
  443.     OptErr = "Bad type given for & option"
  444.     return -3
  445.     }
  446.  
  447.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {    # ]
  448.     if (!GotValue) {
  449.         if (Name != "")
  450.         OptErr = "Variable requires a value -- " Name
  451.         else
  452.         OptErr = "option requires an argument -- " Option
  453.         return -1
  454.     }
  455.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  456.         OptErr = Err
  457.         return -2
  458.     }
  459.     # Mark this as a numeric variable; will be propogated to Options[] val.
  460.     if (ArgType != ":" && ArgType != ";")
  461.         Value += 0
  462.     if ((Instance = ++Options[Option,"count"]) > 1)
  463.         Options[Option,Instance] = Value
  464.     else
  465.         Options[Option] = Value
  466.     }
  467.     # If this is an environ or rcfile assignment & it was given a value...
  468.     else if (!OptionNum && Value != "") {
  469.     UsedValue = 1
  470.     # If the value is "0" or "-" and this is the first instance of it,
  471.     # do not set Options[Option]; this allows an assignment in an rcfile to
  472.     # turn off an option (for the simple "Option in Options" test) in such
  473.     # a way that it cannot be turned on in a later file.
  474.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  475.         Instance = 1
  476.     else
  477.         Instance = ++Options[Option]
  478.     # Save the value even though this is a flag
  479.     Options[Option,Instance] = Value
  480.     }
  481.     # If this is a command line flag and has a - following it in the same arg,
  482.     # it is being turned off.
  483.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  484.     UsedValue = 2
  485.     if (Option in Options)
  486.         Instance = ++Options[Option]
  487.     else
  488.         Instance = 1
  489.     Options[Option,Instance]
  490.     }
  491.     # If this is a flag assignment without a value, increment the count for the
  492.     # flag unless it was turned off.  The indicator for a flag being turned off
  493.     # is that the flag index has not been set in Options[] but it has an
  494.     # instance count.
  495.     else if (Option in Options || !((Option,1) in Options))
  496.     # Increment number of times this flag seen; will inc null value to 1
  497.     Instance = ++Options[Option]
  498.     Options[Option,"num",Instance] = OptionNum
  499.     return UsedValue
  500. }
  501.  
  502. # Option is the option letter
  503. # Value is the value being assigned
  504. # Name is the var name of the option, if any
  505. # ArgType is one of:
  506. # :    String argument
  507. # ;    Non-null string argument
  508. # *    Floating point argument
  509. # (    Non-negative floating point argument
  510. # )    Positive floating point argument
  511. # #    Integer argument
  512. # <    Non-negative integer argument
  513. # >    Positive integer argument
  514. # specGiven is the option specifier character use, if any (e.g. - or +),
  515. # for use in error messages.
  516. # Returns null on success, err string on error
  517. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  518.     if (ArgType == ":")
  519.     return ""
  520.     if (ArgType == ";") {
  521.     if (Value == "")
  522.         Err = "must be a non-empty string"
  523.     }
  524.     # A number begins with optional + or -, and is followed by a string of
  525.     # digits or a decimal with digits before it, after it, or both
  526.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  527.     Err = "must be a number"
  528.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  529.     Err = "may not include a fraction"
  530.     else if (ArgType ~ "[()<>]" && Value < 0)
  531.     Err = "may not be negative"
  532.     # (
  533.     else if (ArgType ~ "[)>]" && Value == 0)
  534.     Err = "must be a positive number"
  535.     if (Err != "") {
  536.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  537.     if (Name != "")
  538.         return ErrStr "variable " substr(Name,1,1) " " Err
  539.     else {
  540.         if (Option == "&")
  541.         Option = Value
  542.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  543.     }
  544.     }
  545.     else
  546.     return ""
  547. }
  548.  
  549. # Note: only the above functions are needed by ProcArgs.
  550. # The rest of these functions call ProcArgs() and also do other
  551. # option-processing stuff.
  552.  
  553. # Opts: Process command line arguments.
  554. # Opts processes command line arguments using ProcArgs()
  555. # and checks for errors.  If an error occurs, a message is printed
  556. # and the program is exited.
  557. #
  558. # Input variables:
  559. # Name is the name of the program, for error messages.
  560. # Usage is a usage message, for error messages.
  561. # OptList the option description string, as used by ProcArgs().
  562. # MinArgs is the minimum number of non-option arguments that this
  563. # program should have, non including ARGV[0] and +h.
  564. # If the program does not require any non-option arguments,
  565. # MinArgs should be omitted or given as 0.
  566. # rcFiles, if given, is a colon-seprated list of filenames to read for
  567. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  568. # by the value of the environment variable HOME.  If a filename begins with
  569. # $, the part from the character after the $ up until (but not including)
  570. # the first character not in [a-zA-Z0-9_] will be searched for in the
  571. # environment; if found its value will be substituted, if not the filename will
  572. # be discarded.
  573. # rcfiles are read in the order given.
  574. # Values given in them will not override values given on the command line,
  575. # and values given in later files will not override those set in earlier
  576. # files, because AssignVal() will store each with a different instance index.
  577. # The first instance of each variable, either on the command line or in an
  578. # rcfile, will be stored with no instance index, and this is the value
  579. # normally used by programs that call this function.
  580. # VarNames is a comma-separated list of variable names to map to options,
  581. # in the same order as the options are given in OptList.
  582. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  583. # searched for in the environment.  If set to -1, all values will be searched
  584. # for in the environment.  Values given in the environment will override
  585. # those given in the rcfiles but not those given on the command line.
  586. # NoRCopt, if given, is an additional letter option that if given on the
  587. # command line prevents the rcfiles from being read.
  588. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  589. # ExclusiveOptions() for a description of exOpts.
  590. # Special options:
  591. # If x is made an option and is given, some debugging info is output.
  592. # h is assumed to be the help option.
  593.  
  594. # Global variables:
  595. # The command line arguments are taken from ARGV[].
  596. # The arguments that are option specifiers and values are removed from
  597. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  598. # The number of elements in ARGV[] should be in ARGC.
  599. # After processing, ARGC is set to the number of elements left in ARGV[].
  600. # The option values are put in Options[].
  601. # On error, Err is set to a positive integer value so it can be checked for in
  602. # an END block.
  603. # Return value: The number of elements left in ARGV is returned.
  604. # Must keep OptErr global since it may be set by InitOpts().
  605. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  606. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  607.     if (MinArgs == "")
  608.     MinArgs = 0
  609.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  610.     optChars)
  611.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  612.     if (ArgsLeft >= 0) {
  613.         OptErr = "Not enough arguments"
  614.         Err = 4
  615.     }
  616.     else
  617.         Err = -ArgsLeft
  618.     printf "%s: %s.\nUse -h for help.\n%s\n",
  619.     Name,OptErr,Usage > "/dev/stderr"
  620.     exit 1
  621.     }
  622.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  623.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  624.     {
  625.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  626.     Err = -e
  627.     exit 1
  628.     }
  629.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  630.     {
  631.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  632.     Err = 1
  633.     exit 1
  634.     }
  635.     return ArgsLeft
  636. }
  637.  
  638. # ReadConfFile(): Read a file containing var/value assignments, in the form
  639. # <variable-name><assignment-char><value>.
  640. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  641. # line and whitespace between the variable name and the assignment character) 
  642. # is stripped.  Lines that do not contain an assignment operator or which
  643. # contain a null variable name are ignored, other than possibly being noted in
  644. # the return value.  If more than one assignment is made to a variable, the
  645. # first assignment is used.
  646. # Input variables:
  647. # File is the file to read.
  648. # Comment is the line-comment character.  If it is found as the first non-
  649. #     whitespace character on a line, the line is ignored.
  650. # Assign is the assignment string.  The first instance of Assign on a line
  651. #     separates the variable name from its value.
  652. # If StripWhite is true, whitespace around the value (whitespace between the
  653. #     assignment char and trailing whitespace on the line) is stripped.
  654. # VarPat is a pattern that variable names must match.  
  655. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  656. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  657. #     a line; no assignment operator is needed.  These variables are set in
  658. #     the output array with a null value.  Lines containing nothing but
  659. #     whitespace are still ignored.
  660. # Output variables:
  661. # Values[] contains the assignments, with the indexes being the variable names
  662. #     and the values being the assigned values.
  663. # Lines[] contains the line number that each variable occured on.  A flag set
  664. #     is record by giving it an index in Lines[] but not in Values[].
  665. # Return value:
  666. # If any errors occur, a string consisting of descriptions of the errors
  667. # separated by newlines is returned.  In no case will the string start with a
  668. # numeric value.  If no errors occur,  the number of lines read is returned.
  669. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  670. FlagsOK,
  671. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  672.     if (Comment != "")
  673.     Comment = "^" Comment
  674.     AssignLen = length(Assign)
  675.     if (VarPat == "")
  676.     VarPat = "."    # null varname not allowed
  677.     while ((Status = (getline Line < File)) == 1) {
  678.     LineNum++
  679.     sub("^[ \t]+","",Line)
  680.     if (Line == "")        # blank line
  681.         continue
  682.     if (Comment != "" && Line ~ Comment)
  683.         continue
  684.     if (Pos = index(Line,Assign)) {
  685.         Var = substr(Line,1,Pos-1)
  686.         Val = substr(Line,Pos+AssignLen)
  687.         if (StripWhite) {
  688.         sub("^[ \t]+","",Val)
  689.         sub("[ \t]+$","",Val)
  690.         }
  691.     }
  692.     else {
  693.         Var = Line    # If no value, var is entire line
  694.         Val = ""
  695.     }
  696.     if (!FlagsOK && Val == "") {
  697.         Errs = Errs \
  698.         sprintf("\nBad assignment on line %d of file %s: %s",
  699.         LineNum,File,Line)
  700.         continue
  701.     }
  702.     sub("[ \t]+$","",Var)
  703.     if (Var !~ VarPat) {
  704.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  705.         LineNum,File,Var)
  706.         continue
  707.     }
  708.     if (!(Var in Lines)) {
  709.         Lines[Var] = LineNum
  710.         if (Pos)
  711.         Values[Var] = Val
  712.     }
  713.     }
  714.     if (Status)
  715.     Errs = Errs "\nCould not read file " File
  716.     close(File)
  717.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  718. }
  719.  
  720. # Variables:
  721. # Data is stored in Options[].
  722. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  723. # Global vars:
  724. # Sets OptErr.  Uses ENVIRON[].
  725. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  726. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  727. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  728. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  729.     split("",filesRead,"")    # make awk know this is an array
  730.     NumVars = split(VarNames,Vars,",")
  731.     TypesInd = Ret = 0
  732.     if (EnvSearch == -1)
  733.     EnvSearch = NumVars
  734.     for (i = 1; i <= NumVars; i++) {
  735.     Var = Vars[i]
  736.     CharOpt = substr(OptList,++TypesInd,1)
  737.     if (CharOpt ~ "^[:;*()#<>&]$")
  738.         CharOpt = substr(OptList,++TypesInd,1)
  739.     Map[Var] = CharOpt
  740.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  741.     # Do not overwrite entries from environment
  742.     if (i <= EnvSearch && Var in ENVIRON &&
  743.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  744.         return Err
  745.     }
  746.  
  747.     numrcFiles = split(rcFiles,fNames,":")
  748.     for (i = 1; i <= numrcFiles; i++) {
  749.     rcFile = fNames[i]
  750.     if (rcFile ~ "^~/")
  751.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  752.     else if (rcFile ~ /^\$/) {
  753.         rcFile = substr(rcFile,2)
  754.         match(rcFile,"^[a-zA-Z0-9_]*")
  755.         envvar = substr(rcFile,1,RLENGTH)
  756.         if (envvar in ENVIRON)
  757.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  758.         else
  759.         continue
  760.     }
  761.     if (rcFile in filesRead)
  762.         continue
  763.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  764.     # may be the same
  765.     filesRead[rcFile]
  766.     if ("x" in Options)
  767.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  768.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  769.     if (retStr > 0)
  770.         READ_RCFILE = 1
  771.     else if (ret != "") {
  772.         OptErr = retStr
  773.         Ret = -1
  774.     }
  775.     for (Var in Lines)
  776.         if (Var in Map) {
  777.         if ((Err = AssignVal(Map[Var],
  778.         Var in Values ? Values[Var] : "",Options,Types[Var],
  779.         Var in Values,Var,0)) < 0)
  780.             return Err
  781.         }
  782.         else {
  783.         OptErr = sprintf(\
  784.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  785.         Lines[Var],rcFile)
  786.         Ret = -1
  787.         }
  788.     }
  789.  
  790.     if ("x" in Options)
  791.     for (Var in Map)
  792.         if (Map[Var] in Options)
  793.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  794.         "/dev/stderr"
  795.         else
  796.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  797.     return Ret
  798. }
  799.  
  800. # OptSets is a semicolon-separated list of sets of option sets.
  801. # Within a list of option sets, the option sets are separated by commas.  For
  802. # each set of sets, if any option in one of the sets is in Options[] AND any
  803. # option in one of the other sets is in Options[], an error string is returned.
  804. # If no conflicts are found, nothing is returned.
  805. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  806. # the exclusions presented by the first set of sets (ab,def,g) if:
  807. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  808. # (a or b is in Options[]) AND (g is in Options) OR
  809. # (d, e, or f is in Options[]) AND (g is in Options)
  810. # An error will be returned due to the exclusions presented by the second set
  811. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  812. # todo: make options given on command line unset options given in config file
  813. # todo: that they conflict with.
  814. function ExclusiveOptions(OptSets,Options,
  815. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  816. SetNum,OSetNum) {
  817.     NumSetSets = split(OptSets,SetSets,";")
  818.     # For each set of sets...
  819.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  820.     # NumSets is the number of sets in this set of sets.
  821.     NumSets = split(SetSets[SetSet],Sets,",")
  822.     # For each set in a set of sets except the last...
  823.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  824.         s1 = Sets[SetNum]
  825.         L1 = length(s1)
  826.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  827.         # If any of the options in this set was given, check whether
  828.         # any of the options in the other sets was given.  Only check
  829.         # later sets since earlier sets will have already been checked
  830.         # against this set.
  831.         if ((c1 = substr(s1,Pos1,1)) in Options)
  832.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  833.             s2 = Sets[OSetNum]
  834.             L2 = length(s2)
  835.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  836.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  837.                 ErrStr = ErrStr "\n"\
  838.                 sprintf("Cannot give both %s and %s options.",
  839.                 c1,c2)
  840.             }
  841.     }
  842.     }
  843.     if (ErrStr != "")
  844.     return substr(ErrStr,2)
  845.     return ""
  846. }
  847.  
  848. # The value of each instance of option Opt that occurs in Options[] is made an
  849. # index of Set[].
  850. # The return value is the number of instances of Opt in Options.
  851. function Opt2Set(Options,Opt,Set,  count) {
  852.     if (!(Opt in Options))
  853.     return 0
  854.     Set[Options[Opt]]
  855.     count = Options[Opt,"count"]
  856.     for (; count > 1; count--)
  857.     Set[Options[Opt,count]]
  858.     return count
  859. }
  860.  
  861. # The value of each instance of option Opt that occurs in Options[] that
  862. # begins with "!" is made an index of nSet[] (with the ! stripped from it).
  863. # Other values are made indexes of Set[].
  864. # The return value is the number of instances of Opt in Options.
  865. function Opt2Sets(Options,Opt,Set,nSet,  count,aSet,ret) {
  866.     ret = Opt2Set(Options,Opt,aSet)
  867.     for (value in aSet)
  868.     if (substr(value,1,1) == "!")
  869.         nSet[substr(value,2)]
  870.     else
  871.         Set[value]
  872.     return ret
  873. }
  874.  
  875. # Returns true if option Opt was given on the command line.
  876. function CmdLineOpt(Options,Opt,  i) {
  877.     for (i = 1; (Opt,"num",i) in Options; i++)
  878.     if (Options[Opt,"num",i] != 0)
  879.         return 1
  880.     return 0
  881. }
  882. ### End of ProcArgs library
  883.